﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.DTO;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base
{
    public partial class Base_RepairOrderFileBusiness : BaseBusiness<Base_RepairOrderFile>, IBase_RepairOrderFileBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public Base_RepairOrderFileBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<Base_RepairOrderFile>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_RepairOrderFile>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_RepairOrderFile, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Base_RepairOrderFileDTO> GetTheDataAsync(string id)
        {
            var q = GetIQueryable().Where(m=>m.Id==id);
            List<Base_RepairOrderFileList> list = new List<Base_RepairOrderFileList>();
            Base_RepairOrderFileDTO listData = new Base_RepairOrderFileDTO();
            var where = LinqHelper.True<Base_RepairOrderFileDTO>();
            foreach (var main in q)
            {
                listData.Id = main.Id;
                listData.Name = main.Name;
                listData.Type = main.Type;
                listData.DeviceId = main.DeviceId;
                listData.FileEnclosure = main.FileEnclosure;
                listData.Remarks = main.Remarks;
                listData.CreateTime = main.CreateTime;
                listData.CreatorId = main.CreatorId;
                listData.Deleted = main.Deleted;
                List<Base_RepairOrderFileListName> DDDDD = new List<Base_RepairOrderFileListName>();
                string sqlMain2 = @"SELECT  a.`Id` AS Id,b.`Name` AS Name,b.`Code` AS Code,b.`Spec` AS Spec,b.`Id` AS DeviceId FROM `Base_RepairOrderFileList`as a
            INNER JOIN Base_Device as  b  on a.DeviceId=b.Id
             where a.ParentId='" + id + "'";
                DDDDD = await Db.GetListBySqlAsync<Base_RepairOrderFileListName>(sqlMain2);
                listData.SubData = DDDDD;
              

            }
            return listData;

        }

        /// <summary>
        /// 创建设备文档保存设备文档分表记录设备
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddDataAsync(Base_RepairOrderFile data)
        {
            string[] DeviceIds = data.DeviceId.Split(',');
            data.DeviceId = "";
            await InsertAsync(data);
            if (DeviceIds.Length>0) {
                    await ExecuteSqlAsync(" DELETE FROM Base_RepairOrderFileList WHERE ParentId ='" + data.Id + "'");
                    List<Base_RepairOrderFileList> base_RepairOrderFileList = new List<Base_RepairOrderFileList>();
                    foreach (var item in DeviceIds)
                    {
                    Base_RepairOrderFileList base_RepairOrderFileLists = new Base_RepairOrderFileList()
                    {
                        Id = IdHelper.GetId(),
                        ParentId = data.Id,
                        Deleted = false,
                        DeviceId = item,
                        CreateTime = DateTime.Now,
                        CreatorId= _operator.UserId,
                    };
                    base_RepairOrderFileList.Add(base_RepairOrderFileLists);
                    }
                    await Db.InsertAsync<Base_RepairOrderFileList>(base_RepairOrderFileList);
                }
        }
        /// <summary>
        /// 编辑设备文档说明操作
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task UpdateDataAsync(Base_RepairOrderFile data)
        {
            await ExecuteSqlAsync(" delete from Base_RepairOrderFileList where ParentId='" + data.Id + "'");
            Base_RepairOrderFile mainData = await Db.GetIQueryable<Base_RepairOrderFile>().Where(s => s.Id == data.Id).FirstOrDefaultAsync();
            if (!mainData.Id.IsNullOrEmpty()) {
                mainData.Id = data.Id;
                mainData.Name = data.Name;
                mainData.Type = data.Type;
                mainData.FileEnclosure = data.FileEnclosure;
                mainData.Remarks = data.Remarks;
                mainData.CreateTime = data.CreateTime;
                mainData.CreatorId = data.CreatorId;
                mainData.Deleted= data.Deleted;
             
            }
          
            List<string> props = GetFieldList(mainData);
            if (props.IsNullOrEmpty())
            {
                await UpdateAsync(mainData);
            }
            else
            {
                await UpdateAsync(mainData);
            }
            string[] DeviceIds = data.DeviceId.Split(',');
            if (DeviceIds.Length > 0)
            {
               
                List<Base_RepairOrderFileList> base_RepairOrderFileList = new List<Base_RepairOrderFileList>();
                foreach (var item in DeviceIds)
                {
                    Base_RepairOrderFileList base_RepairOrderFileLists = new Base_RepairOrderFileList()
                    {
                        Id = IdHelper.GetId(),
                        CreateTime = DateTime.Now,
                        CreatorId = _operator.UserId,
                        ParentId = data.Id,
                        DeviceId=item,
                        Deleted = false
                    };
                    base_RepairOrderFileList.Add(base_RepairOrderFileLists);
                }
                await Db.InsertAsync<Base_RepairOrderFileList>(base_RepairOrderFileList);
            }
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }    
        public async Task<PageResult<Base_RepairOrderFileDTO>> GetDataListInfo(PageInput<PB_ScheduleDetailConditionDTO> input)
        {
            Expression<Func<Base_RepairOrderFile,Base_Device, Base_RepairOrderFileDTO>> select = (a, b) => new Base_RepairOrderFileDTO
            {
              DevName=b.Name,
            };
            var search = input.Search;
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Device>() on a.DeviceId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    
                    select @select.Invoke(a, b);
            if (!input.Search.Name.IsNullOrEmpty()) {
                q = q.Where(x=>x.Name.Contains(input.Search.Name));
            }
            if (!input.Search.Type.IsNullOrEmpty()) {
                q = q.Where(m=>m.Type==input.Search.Type);
            }
            if (!input.Search.DeviceName.IsNullOrEmpty()) {
                //子表数据
                Expression<Func<Base_RepairOrderFileList, Base_Device, Base_RepairOrderFileListName>> selectk = (a, b) => new Base_RepairOrderFileListName
                {

                    Name = b.Name,
                    Code = b.Code,
                };
                selectk = selectk.BuildExtendSelectExpre();
                var k = from a in Db.GetIQueryable<Base_RepairOrderFileList>().AsExpandable()
                        join b in Db.GetIQueryable<Base_Device>() on a.DeviceId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()

                        select @selectk.Invoke(a, b);

                var res = await k.Where(x => x.Name.Contains(search.DeviceName) || x.Code.Contains(search.DeviceName)).ToListAsync();
                var list = res.GroupBy(x => new { x.ParentId }).Select(x => new { ParentId = x.Key.ParentId });
                List<String> names = new List<string>();

                foreach (var item in list)
                {
                    names.Add(item.ParentId);
                }
                q = q.Where(x => names.Contains(x.Id));
            }
            var AA = await q.GetPageResultAsync(input);
            foreach (var itmess in AA.Data)
            {
                string sqlMain = @"SELECT b.`Name` AS Name,b.`Code` AS Code FROM `Base_RepairOrderFileList`as a
INNER JOIN Base_Device as  b  on a.DeviceId=b.Id
 where a.ParentId='" + itmess.Id + "'";
                itmess.SubData = await Db.GetListBySqlAsync<Base_RepairOrderFileListName>(sqlMain); ;
            }
            return AA;
        }

        /// <summary>
        /// pc 通过设备编号获取设备文档明细
        /// </summary>
        /// <param name="input"></param>
        /// <param name="DeviceId"></param>
        /// <returns></returns>
        public async Task<PageResult<Base_RepairOrderFileListDTO>> GetDataListDeviceId(PageInput<PB_ScheduleDetailConditionDTO> input, string DeviceId)
        {
            Expression<Func<Base_RepairOrderFileList, Base_RepairOrderFile,Base_Device, Base_RepairOrderFileListDTO>> select = (a, b,c) => new Base_RepairOrderFileListDTO
            {
                Type = b.Type,
                Name=b.Name,
                FileEnclosure=b.FileEnclosure,
                Remarks=b.Remarks,
                DeviceId=c.Id
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<Base_RepairOrderFileList>().AsExpandable()
                    join b in Db.GetIQueryable<Base_RepairOrderFile>() on a.ParentId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Device>() on a.DeviceId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b,c);
            q = q.Where(m=>m.DeviceId==DeviceId);
            return await q.GetPageResultAsync(input);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}